<?php
/**
 * Created by PhpStorm.
 * User: majiawen
 * Date: 2018/2/5
 * Time: 16:48
 */
namespace app\admin\service;

use app\common\Model\FuncClass;
use app\common\Model\UserShaohuo;
use think\Db;

class UserShaohuoService
{
    //修改成为相应捎货人
    public static function alterShaohuoTypeByUids($uids, $type)
    {

        $UserShaohuo = New UserShaohuo;
        $updateUids = $UserShaohuo->where('uid', 'in', $uids)->column('uid');
        $createUids = array_diff($uids, $updateUids);

        $updateData = [
            'status' => 1,
            'fc_id' => $type,
        ];
        foreach ($createUids as $v) {
            $createData[] = [
                'uid' => $v,
                'status' => 1,
                'fc_id' => $type,
                'apply_status' => 1,
                'exam_status' => 1,
            ];
        }

        //修改捎货人种类
        if ($updateUids) {
            $UserShaohuo->where('uid', 'in', $updateUids)
                ->update($updateData);
        }
        //新建相应捎货人
        if ($createUids) {
            $UserShaohuo->saveAll($createData);
        }
    }

    //移动排序
    public static function alterShaohuoSortByIds($ids, $sort)
    {
        if ($sort == 1) {
            $order = 'sort asc';
            $compare = '<=';
            $orders = 'sort desc';
        }else{
            $order = 'sort desc';
            $compare = '>=';
            $orders = 'sort asc';
        }
        $ids = FuncClass::where('fc_id', 'in', $ids)->where('is_del', 0)->order($order)->select()->toArray();
        // 启动事务
        Db::startTrans();
        try {


            foreach ($ids as $v) {
                $twoFC = FuncClass::where('is_del', 0)->where('sort', $compare, $v['sort'])->order($orders)->limit(2)->select()->toArray();
                if(count($twoFC)==1){
                    Db::rollback();
                    return 2;
                }
                $updata = [
                    [
                        'fc_id' => $twoFC[0]['fc_id'],
                        'sort' => $twoFC[1]['sort'],
                    ],
                    [
                        'fc_id' => $twoFC[1]['fc_id'],
                        'sort' => $twoFC[0]['sort'],
                    ],
                ];
                $FuncClass = new FuncClass();
                $FuncClass->saveAll($updata);
            }


            // 提交事务
            Db::commit();
            return 1;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return 0;
        }
    }
}